package com.shuai.baibi.manager;

import com.shuai.baibi.common.ErrorCode;
import com.shuai.baibi.exception.BusinessException;
import org.redisson.api.RRateLimiter;
import org.redisson.api.RateIntervalUnit;
import org.redisson.api.RateType;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class RedissonManager {
    @Autowired
    private RedissonClient redissonClient;

    /**
     * 做限流
     *
     * @param key 根据key值指定属于该key值的限流器
     */
    public void doRate(String key) {
        RRateLimiter rateLimiter = redissonClient.getRateLimiter(key);  // 获取属于当前key的限流器
        // 对所有的限流器进行限流，最大流量为每秒两次
        rateLimiter.trySetRate(RateType.OVERALL, 2, 1, RateIntervalUnit.SECONDS);
        if (!rateLimiter.tryAcquire()) {
            throw new BusinessException(ErrorCode.TOO_FREQUENT_VISITS);
        }
    }
}
